<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace ckeeper\http;

use ckeeper\services\ZookeeperService;
use Selibra\Di\Annotations\Autowired;
use Selibra\Di\Annotations\Component;
use Selibra\Http\Annotations\Controller;
use Selibra\Http\Annotations\Route;
use Selibra\Http\Lib\HttpController;
use Selibra\Http\Lib\Response;
use Selibra\Http\Route\RouterConfig;
use Selibra\Tools\Console;

#[Component, Controller("/manage/zoo")]
class Zoo extends HttpController
{

    #[Autowired]
    protected ZookeeperService $zookeeperService;

    #[Route("/children")]
    public function children(): Response
    {
        $path = $this->getRequest()->getGet('path');
        if (empty($path)) {
            $path = '/';
        }
        $children = $this->zookeeperService->getChildren($path);
        $result = [];
        foreach ($children as $child) {
            if ($path === '/') {
                $path = '';
            }
            $result[] = [
                'path' => $path . '/' . $child,
                'key' => $child,
                'value' => $this->zookeeperService->getValue($path . '/' . $child),
                'hasChild' => (bool)$this->zookeeperService->getChildren($path . '/' . $child),
            ];
        }
        return $this->success($result);
    }


    #[Route("/addNode", RouterConfig::REQUEST_POST)]
    public function addNode(): Response
    {
        $data = $this->getRequest()->getPost();
        $path = $data['pPath'] . $data['path'];
        $this->zookeeperService->zookeeperInstance()->create($path, $data['value'], [
            [
                'perms' => \Zookeeper::PERM_ALL,
                'scheme' => 'world',
                'id' => 'anyone'
            ]
        ]);
        return $this->success("添加成功");
    }


    #[Route("/editNode", RouterConfig::REQUEST_POST)]
    public function editNode(): Response
    {
        $path = $this->getRequest()->getPost('path');
        $value = $this->getRequest()->getPost('value');
        $this->zookeeperService->zookeeperInstance()->set($path,$value);
        return $this->success("修改成功");
    }


    #[Route("/deleteNode", RouterConfig::REQUEST_DELETE)]
    public function deleteNode(): Response
    {
        $path = $this->getRequest()->getDelete('path');
        $this->zookeeperService->zookeeperInstance()->delete($path);
        return $this->success("删除成功");
    }


}
